package com.kl.reconnect;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class NettyClient {
    private final String host;
    private final int ip;
    private Bootstrap bootstrap;

    public NettyClient(String host, int ip) {
        this.host = host;
        this.ip = ip;
        // 初始化连接参数
        init();
    }


    public static void main(String[] args) throws Exception {
        NettyClient client = new NettyClient("127.0.0.1", 9000);
        client.connect();
    }

    private void init() {
        //客户端需要一个事件循环组
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端启动对象
        //注意客户端使用的不是 ServerBootstrap 而是 Bootstrap
        bootstrap = new Bootstrap();
        //设置相关参数
        bootstrap.group(group) //设置线程组
                .channel(NioSocketChannel.class) // 使用 NioSocketChannel 作为客户端的通道实现
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel channel) {
                        ChannelPipeline pipeline = channel.pipeline();
                        //加解码器和编码器
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        //加入处理器
                        pipeline.addLast(new NettyClientHandler());
                    }
                });
    }


    public void connect() throws InterruptedException {
        ChannelFuture channelFuture = bootstrap.connect(host, ip);
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    future.channel().eventLoop().schedule(() -> {
                        System.err.println("重连服务器...");
                        try {
                            // 迭代重连
                            connect();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }, 3000, TimeUnit.MILLISECONDS);
                } else {
                    System.out.println("服务器连接成功");
                }
            }
        });
        channelFuture.channel().closeFuture().sync();
    }
}
